﻿if (typeof(jQuery) == 'undefined') {
    throw 'jQuery required.';
}

$(function () {

    $('#{parentID}').change(function () {
        if ($(this).val() == '') { return; }
        $.ajax({
            url: '{url}',
            data: {
                id: $('#{parentID}').val()
            },
            type: 'POST',
            success: function (result) {
                var html = '';
                if ('{optionalOption}' != '') {
                    html += '<option value=\'{optionalOption}\'></option>';
                }
                $(result).each(function (i, el) {
                    var idField = el.id ? el.id : el.Id ? el.Id : el.ID;
                    var textField = el.text ? el.text : el.Text ? el.Text : el.TEXT;
                    if (!idField || !textField) {
                        throw 'The action must return a json with the properties \"ID\" and \"Text\" (not case-sensitive)';
                    }
                    html += '<option value=\'' + idField + '\'>' + textField + '</option>';
                });

                $('#{name}').html(html);
            }
        });
    });

    if ($('#{parentID}').val() != '') {
        $('#{parentID}').change();
    }
});